<?php

namespace App\Models;

use App\ModelFilters\UserFilter;
use App\Service\Redis\RedisBaseService;
use Auth;
use Carbon\Carbon;
use DB;
use EloquentFilter\Filterable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, Filterable;

    protected $table = "user";
    public const CREATED_AT = null;
    public const UPDATED_AT = null;

    protected $guarded = [];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    // protected $appends = ['learnQuestionCount', 'learnQuestionCountOfToday', 'questionRate', 'questionRateOfToday', 'hadCourse', 'userLearnCourses'];
    protected $appends = ['learnQuestionCount', 'questionRate', 'questionRateOfToday', 'hadCourse', 'userLearnCourses'];

    /**
     * 获取用户的学习总数
     * @param $v
     * @return int
     * @throws \RedisException
     */
    public function getLearnQuestionCountAttribute($v): int
    {
        return (new RedisBaseService())->getUserStatisticsData('statistics:userLearnQuestionCount', $this->id);
    }

    /**
     * 答题正确率
     * @return float|int
     * @throws \RedisException
     */
    public function getQuestionRateAttribute()
    {
        return (new RedisBaseService())->getUserQuestionRate($this->id);
    }

    public function getQuestionRateOfTodayAttribute() {
        $rate = 0;
        $rightCount = DB::table('qh_user_question_logs')->where('userId', $this->id)->where('result', 1)->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])->count();
        $wrongCount = DB::table('qh_user_question_logs')->where('userId', $this->id)->where('result', 2)->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])->count();

        $sum = $rightCount + $wrongCount;
        if ($sum > 0) {
            $rate = round($rightCount / $sum, 2);
        }

        return $rate;
    }

    /**
     * 用户拥有的学科列表
     * @return array
     */
    public function getHadCourseAttribute(): array
    {
        $courses = [];
        if (request()->is('admin/*')) {
            $courses = $this->course()
                ->select(['qh_courses.id', 'qh_courses.name', 'qh_user_has_course.type', 'qh_user_has_course.userId'])->get();

            foreach ($courses as $course) {
                if ($course->type == 1) {
                    $course->orderId = Order::where('userId', $course->userId)->where('relationId', $course->id)->value('id');
                    $course->cdkeyId = null;
                }
                if ($course->type == 2) {
                    $course->orderId = null;
                    $course->cdkeyId = Qh_Cdkey::where('userId', $course->userId)->where('courseId', $course->id)->value('id');
                }
            }
            $courses = $courses->toArray();
        }

        return $courses;
    }

    public function course(): BelongsToMany
    {
        return $this->belongsToMany(Qh_Course::class, 'qh_user_has_course', 'userId', 'courseId');
    }

    public function modelFilter(): ?string
    {
        return $this->provideFilter(UserFilter::class);
    }

    public function knowledgePost(): BelongsToMany
    {
        return $this->belongsToMany(KnowledgePost::class, 'tiku_user_knowledge_post', 'userId', 'postId');
    }

    public function note(): HasMany
    {
        return $this->hasMany(Note::class, 'userId');
    }

    public function likeNote(): BelongsToMany
    {
        return $this->belongsToMany(Note::class, 'user_like_note', 'userId', 'noteId');
    }

    public function comment(): HasMany
    {
        return $this->hasMany(Comment::class, 'userId');
    }

    public function likeComment(): BelongsToMany
    {
        return $this->belongsToMany(Comment::class, 'user_like_comment', 'userId', 'commentId');
    }

    public function followedSchool(): BelongsToMany
    {
        return $this->belongsToMany(Qh_School::class, 'qh_user_follow_school', 'userId', 'schoolId');
    }

    public function getUserLearnCoursesAttribute() {
        if (!request()->is('admin/*')) return [];

        return DB::table('qh_user_learn_question_logs')
            ->select(
                'qh_user_learn_question_logs.courseId as id',
                'qh_courses.name',
                DB::raw('COUNT(*) as total_count'),
                DB::raw('(SELECT COUNT(*) FROM qh_user_learn_question_logs AS logs_today
                  WHERE logs_today.userId = ' . $this->id . '
                  AND logs_today.courseId = qh_user_learn_question_logs.courseId
                  AND DATE(logs_today.created_at) = CURDATE()) as today_count')
            )
            ->where('qh_user_learn_question_logs.userId', $this->id)
            ->join('qh_courses', 'qh_user_learn_question_logs.courseId', '=', 'qh_courses.id')
            ->groupBy('qh_user_learn_question_logs.courseId', 'qh_courses.name')
            ->orderByDesc('total_count')
            ->get();
    }

    public function document(): BelongsToMany
    {
        return $this->belongsToMany(Document::class, 'qh_user_has_document', 'userId', 'documentId');
    }
}
